<template>
  <div class="ni-select-product">
    <a-select 
      ref="selectRef"
      show-search
      v-model="selectValue"
      :mode="multiple ? 'multiple' : 'default'" 
      style="width: 100%" 
      @select="select"
      @change="change"
      @click.native.stop="skuOpen"
      @search="search"
      @inputKeydown="inputKeydown"
      :notFoundContent="isSku ? '' : undefined"
      :open="isSku ? open : undefined"
      :token-separators="[',']"
      :optionLabelProp="'value'"
    >
      <div slot="dropdownRender" slot-scope="menu">
        <v-nodes :vnodes="menu" />
        <template>
          <a-spin v-if="isSku" :spinning="loading" size="small" style="width: 100%;" :style="items.length === 0 && 'padding: 20px;'">
            <div class="sku-select" @mousedown="e => e.preventDefault()" @click.stop>
              <ul class="ni-select-product-sku-menu">
                <li v-for="(spu, index) in items" :key="spu.productId" :class="activeProductId === spu.productId ? 'active' : ''" @mouseenter="activeItem(index)"  >
                  <div class="spu-name">{{ spu.productName }}</div>
                </li>
              </ul>
            </div>
          </a-spin>
          <a-divider style="margin: 4px 0;" />
          <div
            style="padding: 4px 8px; margin-bottom: 5px;"
            @mousedown="e => e.preventDefault()"
            @click.stop
          >
            <a-checkbox-group v-model="checkedList" :options="filterOptions" @change="onCheckChange" @mousedown="e => e.preventDefault()"/>
          </div>
          <div v-if="isSku && activeProductId" class="ni-select-product-sku" @mousedown="e => e.preventDefault()" @click.stop>
            <div class="ni-select-product-sku-info">
              <div class="ni-select-product-sku-img">
                <img src="https://dummyimage.com/180x180/ace/fff" alt="" width="64">
              </div>
              <div class="ni-select-product-sku-detail">
                <span class="ni-select-product-sku-title">{{ skuDetail.skuName }}</span>
                <div class="ni-select-product-sku-id">
                  商品id: {{ activeProductId }} sku_id: {{ skuDetail.skuId }}
                </div>
              </div>
            </div>
            <div class="ni-select-product-sku-color">
              <a-tag>pink</a-tag>
              <a-tag color="pink">pink</a-tag>
              <a-tag color="blue">pink</a-tag>
              <a-tag color="pink">pink</a-tag>
              <a-tag color="pink">pink</a-tag>
              <a-tag color="pink">pink</a-tag>
            </div>
            <div class="ni-select-product-sku-operation" v-if="skuDetail.skuId">
              <a-button :type="skuCanAdd === -1 ? 'primary' : 'danger' " @click="addSku(skuDetail)">{{ skuCanAdd === -1 ? '添加' : '删除' }}</a-button>
            </div>
          </div>
        </template>
      </div>
      <template v-if="!isSku" @click.stop>
        <a-select-option v-for="item in items" :key="item.productId" :value="item.productId">
          <div class="spu">{{ item.productName }}</div>
        </a-select-option>
      </template>
      <template slot="notFoundContent">
        <div>
          zan wu shu ju
        </div>
      </template>
    </a-select>
  </div>
</template>

<script>
import { Select, Button, Spin, Tag } from 'ant-design-vue'
import { fetchProduct } from './utils/fetchProduct.js'
// const defaultCheckedList = ['手机']
export default {
  props: {
    mode: {
      type: [String],
      defalut: 'sku'
    },
    multiple: {
      type: [Boolean, String, Number],
      defalut: false
    },
    defalutChecked: {
      type: [Array],
      defalut: ['2']
    }
  },
  components: {
    [Select.name]: Select,
    [Button.name]: Button,
    [Spin.name]: Spin,
    [Tag.name]: Tag,
    VNodes: {
      functional: true,
      render: (h, ctx) => {
        return (
          <div class="my-wrapper" ref="wrapper">
            { ctx.props.vnodes }
          </div>
        )
      },
    },
  },
  mounted () {
    window.vm = this
    console.log(window.vm.$refs)
  },
  computed: {
    isSku () {
      return this.mode === 'sku'
    }
  },
  data () {
    return {
      items: [],
      open: false,
      filterOptions: [
        { label: '全部', value: '1'},
        { label: '手机', value: '2'},
        { label: '配件', value: '3'},
        { label: '保护壳', value: '4'},
        // '全部', '手机', '贴膜', '保护壳'
      ],
      checkedList: this.defalutChecked,
      selectValue: [],
      activeProductId: '',
      activeIndex: undefined,
      skuDetail: {},
      skuCanAdd: true,
      loading: false
    }
  },
  watch: {
    activeProductId (newVal, oldVal) {
      if (oldVal) return
      // sku窗口重定位
      console.log('newVal', newVal, 'oldVal', oldVal)
      setTimeout(() => {
        const skuRef = window.document.querySelector('.ni-select-product-sku')
        const windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
        console.log(skuRef, skuRef.getBoundingClientRect())
        if (skuRef && windowWidth - skuRef.getBoundingClientRect().right < 0){
          skuRef.style.transform = 'translateX(-100%)'
          skuRef.style.left = '-10px'
        }
      }, 0);
    }
  },
  methods: {
    onCheckChange (value) {
      console.log(value)
    },
    select (value, option) {
      console.log('select', value, option)
    },
    search (value) {
      clearTimeout(document.timer)
      document.timer = setTimeout(async () => {
        try {
          this.loading = true
          const res = await fetchProduct(value)
          if (res && res.length === 0) {
            // 没找到数据的空白
            return
          }
          if (this.isSku) { // sku默认激活第一条信息，用于渲染sku选择器
            this.items = res
            this.activeIndex = 0
            this.activeItem(this.activeIndex)
          }
        } catch (err) {
          console.error(err)
        } finally {
          this.loading = false
        }
      }, 300)
    },
    // sku列表和气泡启动
    skuOpen () {
      this.open = true
      window.document.addEventListener('click', this.skuOpenChange)
      this.items && !this.items.length && this.search(' ') // 首次加载请求数据，再次加载则不请求
    },
    // 关闭sku列表和气泡
    skuOpenChange () {
      this.open = false
      window.document.removeEventListener('click', this.skuOpenChange)
    },
    change (e) {
      console.log(e)
      this.$emit('change', e)
    },
    // 添加sku，选中
    addSku (info) {
      console.log(info)
      if ( this.skuCanAdd === -1 ) {
        this.selectValue.push(info.skuName)
      } else {
        this.selectValue.splice(this.skuCanAdd, 1)
      }
      this.skuCanAdd = this.selectValue.indexOf(info.skuName)
      if (this.isSku) { this.change(this.selectValue) }
    },
    // sku列表激活
    activeItem (index) {
      this.activeIndex = index
      const porduct = this.items[index]
      this.activeProductId = porduct.productId
      this.skuDetail = porduct.skuChildren[0]
      this.skuCanAdd = this.selectValue.indexOf(this.skuDetail.skuName)
    },
    // sku列表按键事件
    inputKeydown (e) {
      const arrLen = this.items.length
      const { keyCode } = e
      if (keyCode !== 40 && keyCode !== 38) { return }
      if (keyCode === 40) {
        this.activeIndex = this.activeIndex < arrLen - 1 ? ++this.activeIndex : 0
      } else if (keyCode === 38 ) {
        this.activeIndex = this.activeIndex > 0 ? --this.activeIndex : arrLen - 1
      }
      this.activeItem(this.activeIndex)

      // 滚动条位置调整
      const menuDom = document.querySelector('.ni-select-product-sku-menu')
      const itemHeight = 32 // 每一行的高度
      const count = 8 // 够装8个
      if (arrLen <= count || this.activeIndex < count - 2) {
        menuDom.scrollTop = 0 // 置顶
      } else if (arrLen - this.activeIndex < count - 3) {
        menuDom.scrollTop = arrLen * itemHeight // 置底
      } else {
        const position = this.activeIndex - (count - 3)
        menuDom.scrollTop = position * itemHeight
      }
    }
  }
}
</script>

<style lang="scss">
  @import './select-product.scss';

  .my-wrapper { height: 100%; }
  
  ul,li { margin: 0; padding: 0; }

  ul { list-style: none; }

</style>